using System;

namespace Dan.Common.Extend
{
    public static class DateTimeExtend
    {
        /// <summary>
        /// Determines whether [is date time].
        /// </summary>
        /// <param name="obj">The object.</param>
        /// <returns>
        ///   <c>true</c> if [is date time] [the specified object]; otherwise, <c>false</c>.
        /// </returns>
        public static bool IsDateTime(this object obj)
        {
            var str = obj.ToObjString();
            DateTime dt = DateTime.MinValue;
            return DateTime.TryParse(str, out dt);
        }
        /// <summary>
        /// 如果能轉化返回時間,不能返回null
        /// </summary>
        /// <param name="obj">The object.</param>
        /// <param name="defaultValue">The default value.</param>
        /// <returns></returns>
        public static DateTime SafeToDateTime(this object obj, DateTime? defaultValue = null)
        {
            var str = obj.ToObjString();
            DateTime dt = DateTime.MinValue;
            if (DateTime.TryParse(str, out dt))
            {
                return dt;
            }
            if (defaultValue != null)
            {
                return defaultValue.GetValueOrDefault();
            }
            return DateTime.MinValue;
        }

        /// <summary>
        /// To the date string.
        /// </summary>
        /// <param name="date">The date.</param>
        /// <param name="format">The format.</param>
        /// <returns></returns>
        public static string ToDateStr(this DateTime date, string format = "yyyy-MM-dd")
        {
            return date.ToString(format);
        }
        
        /// <summary>
        /// string型转换为DateTime型,转换失败返回缺省值
        /// </summary>
        /// <param name="str">要转换的字符串</param>
        /// <param name="def">缺省值</param>
        /// <returns>转换后的DateTime类型结果</returns>
        public static DateTime StrToDateTime(string str, DateTime def)
        {
            if (!DateTime.TryParse(str, out DateTime result))
            {
                return def;
            }
            return result;
        }
    }
}